<template>
  <el-dialog
    v-model="dialogVisible"
    title="设置行数限制"
    width="400px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules">
      <el-form-item label="最小行数" prop="minLineCount">
        <el-input-number
          v-model="form.minLineCount"
          :min="1"
          :step="1"
          step-strictly
          class="!w-[100%]"
        />
      </el-form-item>
      <el-form-item label="最大行数" prop="maxLineCount">
        <el-input-number
          v-model="form.maxLineCount"
          :min="1"
          :step="1"
          step-strictly
          class="!w-[100%]"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitForm">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { updateServiceLineLimits } from "@/api/adminThirdPartyApi";
import { message } from "@/utils/message";

interface UserForm {
  minLineCount: number;
  maxLineCount: number;
}
const dialogVisible = ref(false);
const emits = defineEmits(["refresh"]);
const form = reactive<UserForm>({
  minLineCount: 0,
  maxLineCount: 0
});
const serviceId = ref("");
const rules: FormRules = {
  minLineCount: [
    {
      required: true,
      message: "请输入最小行数",
      trigger: "blur"
    }
  ],
  maxLineCount: [
    {
      required: true,
      message: "请输入最大行数",
      trigger: "blur"
    }
  ]
};

const serviceForm = ref<FormInstance>();
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
  serviceForm.value?.clearValidate();
};
const submitLoading = ref(false);

const submitForm = () => {
  serviceForm.value?.validate(async valid => {
    if (valid) {
      try {
        const { maxLineCount, minLineCount } = form;
        if (maxLineCount <= minLineCount) {
          message("最大行数不能小于等于最小行数", { type: "error" });
          return;
        }
        submitLoading.value = true;
        const { message: text } = await updateServiceLineLimits(
          serviceId.value,
          form
        );
        message(text || "设置成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      } catch (error) {
        console.error(error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};
const open = ({ minLineCount, maxLineCount, id }) => {
  serviceId.value = id;
  form.minLineCount = minLineCount ?? 1;
  form.maxLineCount = maxLineCount ?? 1;
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
